<script setup lang="ts">
import AniFade from './AniFade.vue'

import { onUnmounted, ref } from 'vue'

import { random } from '../stores/util'
function generateRaws(take: number) {
  const list = 'a'.repeat(take * 2).split('').map((_, i) => {
    const oo = ['+', '-']
    const oi = random(0, 9) % 2
    return {
      ii: i,
      n1: random(12, 255),
      o2: oo[oi],
      n2: random(11, 99),
      o3: oo[1 - oi],
      n3: random(2, 9),
      result: "",
      check: "",
      eq: 0,
    }
  }).filter(e => {
    if (e.o2 === "+" && e.o3 === "-") {
      e.eq = e.n1 + e.n2 - e.n3
    } else if (e.o2 === "-" && e.o3 === "+") {
      e.eq = e.n1 - e.n2 + e.n3
    }
    return e.eq >= 0 && e.eq <= 999
  }).slice(0, take)
  return list
}

const take = 30
const raws = generateRaws(take)
const data = ref({
  take, raws, live: 0
})

const time = setInterval(() => {
  if (checked.value) return
  data.value.live++
}, 1000)

onUnmounted(() => {
  clearInterval(time)
})

const checked = ref(false)
function check() {
  data.value.raws.forEach((e) => {
    const check = e.result.trim() === e.eq.toString()
    e.check = check ? 'ok' : 'err'
  })
  checked.value = true
}

function reGenerateRaws() {
  data.value.raws = generateRaws(data.value.take)
  checked.value = false
  data.value.live = 0
}

</script>
<template>
  <div>
    <div class="w-full py-2 flex flex-row gap-2">
      <div class="py-2">加减题目</div>
      <input type="button" value="检查" @click="check" :disabled="checked" class="btn btn-yellow btn-sm">
      <input type="number" class="input sm w-15" v-model="data.take" />
      <button type="button" @click="reGenerateRaws" class="btn btn-red btn-sm">生成</button>
    </div>
    <div class="flex flex-wrap gap-2 border rounded px-4 py-4">
      <div v-for="calc in data.raws" :key="calc.ii" class="w-60 h-10">
        <div class="flex flex-row gap-2">
          <div>{{ calc.n1 }} {{ calc.o2 }} {{ calc.n2 }} {{ calc.o3 }} {{ calc.n3 }}</div>
          <div> = </div>
          <div> <input type="text" class="w-12 input sm line" v-model="calc.result" /></div>
          <AniFade>
            <div class="border-b border-red-800 text-red-800" v-show="calc.check === 'err'">X</div>
          </AniFade>
        </div>
      </div>
      <div class="w-60 h-10">
        用时 {{ data.live }} 秒
      </div>
    </div>
  </div>
</template>
